package net.yunzhanyi.client.interceptor;

import net.yunzhanyi.client.annotation.CheckWebLogin;
import net.yunzhanyi.client.constant.AccountConstant;
import net.yunzhanyi.client.domain.dto.ClientLoginUser;
import net.yunzhanyi.client.service.TokenService;
import net.yunzhanyi.common.core.exception.NotLoginException;
import net.yunzhanyi.common.core.utils.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author qiuxin
 * @code LoginInterceptor
 * @date 2022/3/27
 * description：
 */
@Component
public class LoginInterceptor implements AsyncHandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 拦截处理代码
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String token = tokenService.getWebToken(request);
        ClientLoginUser clientLoginUser = null;
        if (StringUtils.isNotEmpty(token) && !"null".equals(token)) {
            clientLoginUser = tokenService.parseWebToken(token);
            if (clientLoginUser == null || clientLoginUser.getAid() == null) {
                clientLoginUser = null;
            }
            request.setAttribute("loginUser", clientLoginUser);
        }
        if (method.getAnnotation(CheckWebLogin.class) != null) {
            if (clientLoginUser == null) {
                throw new NotLoginException(AccountConstant.VERIFICATION_EXPIRED);
            }
        }
        return true;
    }
}
